package com.ruoyi.api;

import java.util.HashMap;
import java.util.Map;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.WxApiLoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.service.WxApiTokenService;
import com.ruoyi.framework.web.service.WxApiTokenService;
import com.ruoyi.wxapp.domain.WxappConfig;
import com.ruoyi.wxapp.domain.WxappUsers;
import com.ruoyi.wxapp.service.IWxappConfigService;
import com.ruoyi.wxapp.service.IWxappUsersService;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import com.alibaba.fastjson2.JSONObject;

import com.alibaba.fastjson2.JSON;

@Api(tags= "微信小程序-用户接口", description="登录接口")
@RestController
@RequestMapping("/wxapi/")
@Slf4j
public class WxLoginController {

    @GetMapping("test")
    public AjaxResult test() {
        return AjaxResult.success("小程序 api 调试成功");
    }

    @Autowired
    private IWxappUsersService iWxappUsersService;

    @Autowired
    private IWxappConfigService iWxappConfigService;

    @Autowired
    private WxApiTokenService wxApiTokenService;

    /**
     * 你自己的微信小程序APPID
     */

    private String AppID = "";
    /**
     * 你自己的微信APP密钥
     */
    private String AppSecret = "";

    /**
     * 登录时获取的 code（微信官方提供的临时凭证）
     * 
     * @param object
     * @return
     */
    @ApiOperation("微信小程序登录")
    @PostMapping("/wxlogin")
    public AjaxResult wxLogin(@RequestBody JSONObject object) {
        // 微信官方提供的微信小程序登录授权时使用的URL地址
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        System.out.println("------->code: "+ object);
        /**
         * 拼接需要的参数
         * appid = AppID 你自己的微信小程序APPID
         * js_code = AppSecret 你自己的微信APP密钥
         * grant_type=authorization_code = code 微信官方提供的临时凭证
         */

        WxappConfig config =  iWxappConfigService.selectWxappConfig();
        if (config == null) {
            return AjaxResult.error(500, "请先设置 appid 和 secret");
        }
        this.AppID = config.getAppid();
        this.AppSecret = config.getAppSecret();

        String params = StrUtil.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", AppID, AppSecret,
                object.get("code"));
        // 开始发起网络请求,若依管理系统自带网络请求工具，直接使用即可
        String res = HttpUtils.sendGet(url, params);
        System.out.println("---------> 输出请求到的结果: ");
        System.out.println(res);

        JSONObject jsonObject = JSON.parseObject(res);
        String session_key = (String) jsonObject.get("session_key");
        String openid = (String) jsonObject.get("openid");
        if (StrUtil.isEmpty(openid)) {
            return AjaxResult.error("未获取到openid");
        }
        String token = UUID.randomUUID().toString();
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("session_key", session_key);
        data.put("openid", openid);
        data.put("state", true);
        data.put("nickName", object.get("nickName"));
        data.put("avatarUrl", object.get("avatarUrl"));
        data.put("gender", object.get("gender"));
        /** 先通过openid来查询是否存在 */
        WxappUsers wxuser = iWxappUsersService.selectUserByOpenId(openid);
        if (wxuser == null) {
            /** 如果不存在就插入到我们的数据库里 */
            WxappUsers newWxUser = new WxappUsers();
            newWxUser.setNickname(String.valueOf(object.get("nickName")));
            newWxUser.setGender((Integer) object.get("gender"));
            newWxUser.setAvatar(String.valueOf(object.get("avatarUrl")));
            newWxUser.setOpenid(openid);
            newWxUser.setCreateTime(DateUtils.getNowDate());
            newWxUser.setCreateBy("whisky");
            iWxappUsersService.insertWxappUsers(newWxUser);
            wxuser = newWxUser;
            data.put("id", newWxUser.getId());
        } else {
            /** 如果存在就更新数据库里原有的数据 */
            wxuser.setUpdateTime(DateUtils.getNowDate());
            wxuser.setUpdateBy("whisky");
            iWxappUsersService.updateWxappUsers(wxuser);
            data.put("id", wxuser.getId());
        }

        data.put("token", wxApiTokenService.createToken(wxuser));

        log.info("------> 用户信息："+data);

        /** 返回结果集到前段 */
        return AjaxResult.success(data);
    }
}
